<template>

  <j-modal
    :zIndex='zIndex'
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭" okText="确认"> 
    <div style="width:100%">
       <slot name="header"  :customParam="customParam" :queryParam="queryParam">
      </slot>
    </div>
     <div style="width:100%;margin-bottom:20px;">
        <a-input-search :placeholder="searchPlaceholder" allow-clear enter-button v-model="queryParam[keywordKey]" @search="searchQuery" />

            </div>
            <p style="text-align: center;" v-if="!!emptyAddData.emptyLink">
            <a-button type="link"  @click="handleEmptyAddData" >{{emptyAddData.emptyText||'点击新建数据吧'}}</a-button>
            </p>
            <div v-if="showSelection" class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <span  style="margin-left: 24px" v-show="!!rowNames">{{ rowNames }}</span>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true,y: 300}"
        bordered
        :rowKey="rowKey"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :filterMultiple="isAllSelect"
        :rowSelection="showSelection?{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type:checkType}:null"
        @change="handleTableChange"
        :customRow="customRow">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <span slot="receiveUser" slot-scope="text, record">
           <a-input placeholder="点击选择" v-model="record.realname" @click="selectUser(record)" />
        </span>
         <span slot="link" slot-scope="text, record">
          <a @click="handlColumnLink(record)">{{text}}</a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
        </span>

      </a-table>
       
  </j-modal>
</template>

<script>
import { strNotNull } from '@/utils/common.js'
 import cloneDeep from 'lodash/cloneDeep'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { mixinDevice } from '@/utils/mixin'
  import { httpAction, getAction,postAction } from '@/api/manage'
  export default {
    name: 'TableSelectModal',
     mixins:[JeecgListMixin,mixinDevice],
    components: {

    },
    props: {
      isAllSelect:{
        //默认多选
        type:Boolean,
        default:true,
        required:false,
      },
      limit:{
        //限制数量
        type:Number,
        
        default:0,
        required:false
      },
      importColumns:{
        //传入表头
        type:Array,
        default:[],
        required:true
      },
       params:{
            Type: Object,
            default: ()=>{return {}},
            require:false
      },
      keywordKey:{
          Type:String,
          default: 'keyword',
          require:false
      },
       searchPlaceholder: {
          Type: String,
          default: '请输入关键词进行模糊查询',
           require:false
      },
      title:{
          Type:String,
          default:'选择数据',
        
      },
      width:{
          Type:Number,
          default:800
      },
      listUrl:{
          type:String,
          
      },
      emptyAddData:{
        require:false,
        type:Object,
        default:()=>{
          return {
            emptyLink:null,
            emptyText:null
            }
        }
      },
      rowKey:{
          Type:String,
          default:'defaultRowIndex',
          require:false,

      },
       method:{
          //请求方法
          Type:String,
          default:'get',
          require:false,
      },
      rowName:{
          //选择回显名称
          Type:String,
          default:'',
          require:false,
      },
      defaultCustomParam:{
        require:false,
        type:Object,
        default:()=>{
          return {
            
            }
        }},
        showSelection:{
          type:Boolean,
          default:true,
          required:false,
        },
    },
    data () {
      return {
        zIndex:1001,
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10','20', '50'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
      saveData:[],
      disableMixinCreated:true,
      currSel: {},
      originTargetKeys: [],
      isorter:{
        column: '',
        order: 'desc',
      },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
    
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],

        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:(t,r,index)=>  {
              r.rowIndex =  parseInt(index)+1
            
              return parseInt(index)+1;
            }
          },
          
          {
            title:'公司名称',
            align:"center",
            dataIndex: 'name'
          }
        ],
        checkType:this.isAllSelect?'checkbox':'radio',
        url: {
          list: "",
        },
        dictOptions:{},
        superFieldList:[],

        visible: false,
        disableSubmit: false,
        queryMethod : this.method,
       
        rowNames:'',
        rowKeys:'',
        customParam:this.defaultCustomParam,
      }
    },
    watch: {
      importColumns:function(val){
          this.initColums(val)
      },
      selectionRows:function(rows){
        this.rowNames = ''
        if(this.rowName){
         let rowNames = rows.map(item=>{return item[this.rowName]}) || []
         this.rowNames = rowNames.join(',')
        }
        let ids = rows.map(item=>{return item[this.rowKey]}) || []
        this.rowKeys = ids.join(',')
        
        
      },
     
    },
   
    methods: {
      handleEmptyAddData(){
        window.open(this.emptyAddData.emptyLink,'_blank')
      },
      handlColumnLink(record){
        
        this.$emit("handlColumnLink",record);
      },
      initColums(val){
            var rowIndex = [
           
            {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender: (t,r,index)=> {
              r.rowIndex =  parseInt(index)+1
              r.defaultRowIndex = this.ipagination.current +'-'  + r.rowIndex
              return parseInt(index)+1;
            }
          }]
          this.columns = [...rowIndex,...val]
      }, 
      open (urlList) {
        this.visible=true
        this.$nextTick(()=>{
          this.customParam = this.defaultCustomParam
          this.url.list = this.listUrl;
          this.queryParam =cloneDeep(this.params)
        this.initColums(this.importColumns)
        this.onClearSelected()
        this.loadData(1);
        })
      },
      edit (record) {
        this.visible=true
        this.$nextTick(()=>{
          this.$refs.realForm.edit(record);
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        //返回数组
         var that = this;
         if(!that.showSelection){
            that.submitCallback()
         }
        if(that.selectedRowKeys.length <= 0){
           this.$message.warning('请选择数据！');
           return;
        }
        
        if(!that.isAllSelect && that.selectedRowKeys.length != 1){
            this.$message.warning('请选择一行数据！');
           return;
        }
         if(that.limit !=0 && that.selectedRowKeys.length > that.limit){
            this.$message.warning(`最多选择${that.limit}行数据！`);
           return;
        }
        var res = []
        for (var a = 0; a < that.selectedRowKeys.length; a++) {
          let rowIndex = that.selectedRowKeys[a] ;
          let arr = that.selectionRows.filter(item=>{return item[this.rowKey] == rowIndex})
          res.push(...arr)
          
        }
        this.$emit('back',[this.rowKeys,this.rowNames])
        
        this.$emit('ok',res);
        that.onClearSelected();
        
      },
      submitCallback(){
        this.$emit('ok');
        this.visible = false;
      },
      handleCancel () {
        this.close()
      },
       handleDelete: function () {

    
      
    },
    handleList(){

    },
    modalFormOk(res){
      this.dataSource.push(res)
    },
    customRow(record,index)  {
    return {
      
      on: { // 事件
        click: (event) => { // 点击行
          let that = this
          if(!that.showSelection){
            return
          }
           let key = record[this.rowKey]
              if (!that.isAllSelect) {
                that.selectedRowKeys = [key]
                that.selectionRows = [record]
              } else {
                let index = that.selectedRowKeys.indexOf(key)
                let rowIndex =  that.selectionRows.findIndex(item=>{return item[this.rowKey] == key})
                if (index === -1) {
                  that.selectedRowKeys.push(key)
                  that.selectionRows.push(record)
                } else {
                  that.selectedRowKeys.splice(index, 1)
                  if(rowIndex != -1){
                    that.selectionRows.splice(rowIndex, 1)
                  }
                }
              }
        },      
        
      },

    }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
          let that = this
          this.selectedRowKeys = selectedRowKeys;
          let rows = []
          selectedRowKeys.forEach(key=>{
            let arr = that.selectionRows.filter(item=>{return item[that.rowKey] == key})
            let selectionArr =  selectionRows.filter(item=>{return item[that.rowKey] == key})
            if(arr.length==0){
              arr = selectionArr
            }
            
            rows = rows.concat(arr)
          })

          this.selectionRows = rows;
        },
    }
  }
</script>
<style lang="less" scoped>

/deep/ .ant-spin-container > .ant-table > .ant-table-content > .ant-table-scroll > .ant-table-header {
    overflow: hidden !important;
    overflow-y: scroll !important;//只加了这一句话
    margin-bottom: 0 !important;
}

</style>